package com.huishu.commons.utlis;

import com.huishu.commons.pojo.vo.ExceptionEmailVO;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 邮件发送
 */
public class EmailUtils {

    private static final String HOST = "smtp.qq.com";

    private static final String USERNAME = "2363979105@qq.com";

    private static final String PASSWORD = "lqsgnviqycardjac";


    public static void sendErroeEmail(ExceptionEmailVO errorEmailVO){
        MimeMessage mimeMessage = createMail().createMimeMessage();
        StringBuilder sb = new StringBuilder();
        sb.append("<html><head></head>");
        sb.append("<body>");
        sb.append("开发环境:" + errorEmailVO.getProfile());
        sb.append("</p>");
        sb.append("接口地址:" + errorEmailVO.getApi());
        sb.append("</p>");
        sb.append("参数:" + errorEmailVO.getParams());
        sb.append("</p>");
        sb.append("错误信息:" + errorEmailVO.getErrorMsg());
        sb.append("</p>");
        sb.append("</body>");
        sb.append("</html>");
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            mimeMessageHelper.setFrom("2363979105@qq.com");
            mimeMessageHelper.setTo(new String[]{"2363979105@qq.com"});
            mimeMessageHelper.setSubject(errorEmailVO.getServerName() + "：出错误啦");
            mimeMessageHelper.setText(sb.toString(), true);
            createMail().send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        System.out.println("Sent message successfully....");
    }

    public static JavaMailSenderImpl createMail() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(HOST);
        javaMailSender.setPort(465);
        javaMailSender.setUsername(USERNAME);
        javaMailSender.setPassword(PASSWORD);
        Properties properties = new Properties();
        properties.setProperty("mail.host", "smtp.qq.com");
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.smtp.port", "465");
        properties.setProperty("mail.smtp.socketFactory.port", "465");
        javaMailSender.setJavaMailProperties(properties);
        return javaMailSender;
    }

    public static void main(String[] args){
        ExceptionEmailVO exceptionEmailVO = new ExceptionEmailVO();
        exceptionEmailVO.setApi("会员状态更新");
        exceptionEmailVO.setErrorMsg("更新出错了！");
        EmailUtils.sendErroeEmail(exceptionEmailVO);
    }
}
